package com.yupi.yupibackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yupibackend.constants.UserConstant;
import com.yupi.yupibackend.exception.BusinessException;
import com.yupi.yupibackend.exception.ErrorCode;
import com.yupi.yupibackend.exception.ThrowUtils;
import com.yupi.yupibackend.mapper.UserMapper;
import com.yupi.yupibackend.model.entity.User;
import com.yupi.yupibackend.model.req.user.UserLoginRequest;
import com.yupi.yupibackend.model.req.user.UserRegisterRequest;
import com.yupi.yupibackend.model.req.user.UserUpdateRequest;
import com.yupi.yupibackend.model.vo.UserVo;
import com.yupi.yupibackend.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

/**
* @author 86178
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-05-03 19:41:39
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{


    /**
     *  用户注册
     * @param userRegisterRequest
     * @return
     */
    @Override
    public Long userRegister(UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest==null,ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        //1.参数校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        String encryptPassword = this.getEncryptPassword(userPassword);
        //2. 账号不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        //3. 插入数据
        User user = new User();
        BeanUtil.copyProperties(userRegisterRequest, user);
        user.setUserPassword(encryptPassword);
        boolean result = this.save(user);
        if(!result){
         throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户注册失败");
        }
        return user.getId();
    }

    /**
     * 用户登录
     * @param userLoginRequest
     * @param request
     * @return
     */
    @Override
    public UserVo userLogin(UserLoginRequest userLoginRequest,HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest==null,ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        //1.参数校验
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        //2.加密
        String encryptPassword = this.getEncryptPassword(userPassword);

        //3.查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        // 4. 记录用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return this.getUserVo(user);
    }

    /**
     * 用户更新
     * @param userUpdateRequest
     * @return
     */
    @Override
    public boolean userUpdate(UserUpdateRequest userUpdateRequest) {
        ThrowUtils.throwIf(userUpdateRequest==null,ErrorCode.PARAMS_ERROR);
        String username = userUpdateRequest.getUsername();
        String userAccount = userUpdateRequest.getUserAccount();
        String userAvatar = userUpdateRequest.getUserAvatar();
        Integer gender = userUpdateRequest.getGender();
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (username.length() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名过长");
        }
        User user = new User();
        BeanUtil.copyProperties(userUpdateRequest, user);
        boolean result = this.updateById(user);
        if(!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户更新失败");
        }
        return true;
    }

    /**
     * 用户登出
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null||currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);//移除用户的登录态
        return true;
    }


    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null||currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long userId = currentUser.getId();//获取最新的对象
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        currentUser=user;
        return currentUser;
    }

    /**
     * 密码加密
     * @param password
     * @return
     */
    @Override
    public String getEncryptPassword(String password) {
        String SALT="lxz";
        return DigestUtils.md5DigestAsHex((SALT+password).getBytes());
    }

    /**
     * 获取UserVo
     * @param user
     * @return
     */
    @Override
    public UserVo getUserVo(User user) {
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user, userVo);
        return userVo;
    }

    /**
     * 判断用户是否是管理员
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserConstant.ADMIN_ROLE.equals(user.getUserRole());
    }
}




